<template>
  <div>
    <header>
      <Card>
        <section class="mine_header">
          <van-image round width="56px" height="56px" :src="info?.avatar" v-if="info?.avatar" />
          <section class="mine_header_info">
            <section class="mine_header_info_name">{{ info?.nickname }}</section>
            <section class="mine_header_info_desc">{{ greeting }}</section>
          </section>
        </section>
      </Card>
    </header>
    <main>
      <van-calendar type="multiple" title="我的植物养护计划" :poppable="false" switch-mode="year-month" :show-confirm="false"
        class="calendar" :default-date="defaultDate" readonly />
    </main>
    <footer style="margin-top: 8px;">
      <van-swipe-cell v-for="item in planList" :key="item?.id">
        <Card >
          <section class="card">
            <img class="card_img" :src="item?.cover" />
            <section class="card_content">
              <section class="card_content_matter">养护事项：{{ matterEnum?.[item?.matter] }}</section>
              <section class="card_content_time">计划时间：{{ item?.planDate }} {{ item?.planTime }}</section>
              <section class="card_content_remark van-multi-ellipsis--l1" v-if="item?.remarks">备注：{{item?.remarks  }}</section>
              <section class="card_content_action" >
                <van-space>
                  <van-button round type="success" color="#09BB07" size="mini" @click="handleLookPlant(item)">查看植物</van-button>
                  <van-button round type="success" color="#09BB07" size="mini" :disabled="isSigned(item)" @click="handleSign(item)">{{ item?.signed ? '已打卡': '打卡' }}</van-button>
                  <van-button round type="success" color="#09BB07" size="mini" v-if="isPastDate(item) && !item?.signed" @click="handleSupplement(item)">补卡</van-button>
                </van-space>
              </section>
            </section>
          </section>
        </Card>
        <template #right>
          <van-button square text="删除" type="danger" @click="handleDeletePlan(item)" class="delete-button" />
        </template>
      </van-swipe-cell>
    </footer>

    <van-dialog v-model:show="show" :title="title" show-cancel-button @confirm="handleConfirm" @cancel="handleCancel">
      <van-form>
        <van-cell-group inset>
          <van-field v-model="formState.remarks" name="remarks" label="备注" placeholder="请输入备注" />
        </van-cell-group>
      </van-form>
    </van-dialog>

    <van-dialog v-model:show="show4" title="添加养护计划" show-cancel-button @confirm="handleConfirm1" @cancel="handleCancel1">
      <van-form>
        <van-cell-group inset>
          <van-field v-model="formState1.matterName" name="matterName" label="养护事项" placeholder="请选择养护事项"
            @click="show3 = true" />
          <van-field v-model="formState1.signDate" name="signDate" label="补卡日期" placeholder="请选择补卡日期"
            @click="show1 = true" />
          <van-field v-model="formState1.signTime" name="signTime" label="补卡时间" placeholder="请选择补卡时间"
            @click="show2 = true" />
          <van-field v-model="formState1.remarks" name="remarks" label="备注" placeholder="请输入备注" />
        </van-cell-group>
      </van-form>
    </van-dialog>
    <van-popup v-model:show="show1" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-date-picker :min-date="new Date()" title="请选择计划日期" @confirm="handleDateConfirm" @cancel="show1 = false" />
    </van-popup>
    <van-popup v-model:show="show2" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-time-picker :columns-type="['hour', 'minute','second']" title="选择提醒时间" @confirm="handleTimeConfirm" @cancel="show2 = false" />
    </van-popup>
    <van-popup v-model:show="show3" position="bottom" :style="{ height: '40%', backgroundColor: '#fff' }">
      <van-picker title="养护事项" :columns="columns" @confirm="handleMatterConfirm" @cancel="show3 = false" />
    </van-popup>
    <section style="height: 100px;"></section>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { useRouter } from 'vue-router';
import { showToast, showConfirmDialog } from 'vant';
import Card from '@/components/Card/index.vue';
import { getUserInfo } from '@/apis/user';
import { getPlanList,deletePlan } from '@/apis/plan';
import {addSign} from '@/apis/sign';
import dayjs from 'dayjs';

const router = useRouter();

const title = ref('');


const columns = [
  { text: '浇水', value: 1 },
  { text: '施肥', value: 2 },
  { text: '光照调整', value: 3 },
  { text: '修剪', value: 4 },
  { text: '病虫防治', value: 5 },
  { text: '换盆', value: 6 },
];


const matterEnum = {
  1: '浇水',
  2:"施肥",
  3:"光照调整",
  4:"修剪",
  5:"病虫防治",
  6:"换盆"
};

let timer = null;
const info = ref({});
const currentTime = ref(Date.now());

const defaultDate = ref([dayjs().toDate()]);

const planList = ref([]);

const show = ref(false);

const show1 = ref(false);
const show2 = ref(false);
const show3 = ref(false);
const show4 = ref(false);


const sign = ref({});

const formState = ref({
  remarks: ''
});

const formState1 = ref({
  planId: "",
  matter: "",
  signDate: "",
  remarks: "",
  signTime: "",
  matterName:""
});

const init = async () => {
  try {
    const { data = {} } = await getUserInfo();
    info.value = data;

  } catch (error) {
    console.log(error, 'init-userInfo-error')
  }
};


const planListInit = async () => {
  try {
    const res = await getPlanList({ pageNum: 1, pageSize: 100 });
    if (res?.code === 200) {
      defaultDate.value = res?.data?.list?.map(item => {
        return dayjs(item?.planDate)?.toDate();
      });
      planList.value = res?.data?.list || [];
    }
  } catch (error) {
    console.log(error, 'planListInit-error')
  }
};

const greeting = computed(() => {
  const hour = dayjs(currentTime.value).hour();

  if (hour >= 5 && hour < 9) {
    return '早上好';
  } else if (hour >= 9 && hour < 12) {
    return '上午好';
  } else if (hour >= 12 && hour < 14) {
    return '中午好';
  } else if (hour >= 14 && hour < 18) {
    return '下午好';
  } else if (hour >= 18 && hour < 24) {
    return '晚上好';
  } else {
    return '夜深了，早点休息';
  }
});

const isSigned  = computed(()=>{

  return (item) => {

    const isCurrent = dayjs(item?.planDate).isSame(dayjs().format('YYYY-MM-DD'));
    if(isCurrent && !item?.signed){
      return false;
    }
    return true;

  }
});


const isPastDate = computed(() => {
  return (item) => {
    return dayjs(item?.planDate).isBefore(dayjs(), 'day');
  }
});


const handleLookPlant = (item) => {
  router.push(`/plant/detail/${item?.plantId}`)
};


const handleDeletePlan = async (item) => {

  showConfirmDialog({
    title: `确定删除该植物计划吗？`,
    confirmButtonColor: "#f50"
  })
    .then(async () => {
      try {
        const res = await deletePlan(item?.id);
        if (res?.code === 200) {
          showToast('已删除计划');
          planListInit();
          return
        }
        showToast(res?.msg);

      } catch (error) {
        console.log(error, 'error');

      }

    })
    .catch(() => {

    });
};

const handleSign = async (item) => {
  console.log(item,'item');
  show.value = true;
  sign.value = item;
  title.value = '打卡';
};


const handleConfirm =  async() => {

  try {
    const res = await addSign({
      planId: sign?.value?.id,
      matter:sign?.value?.matter,
      remarks: formState?.value?.remarks
    });
    if(res?.code === 200){
      showToast('打卡成功');
      formState.value = {};
      sign.value = {};
      show.value = false;
      planListInit();
    }
  } catch (error) {
    formState.value = {};
    sign.value = {};
    console.log(error, 'add-sign-error');

  }

};

const handleSupplement = (item) => {
  show4.value = true;
  sign.value = item;
  formState1.value.planId = item?.id;
  title.value = '补卡';
};
const handleCancel = () => {
  formState.value = {};
  show.value = false;
};


const handleConfirm1 = async () => {
  try {
    const res = await addSign(formState1.value);
    if(res?.code === 200){
      show4.value = false;
      showToast('补卡成功');
      planListInit();
      formState1.value = {};
    }
  } catch (error) {
    console.log(error, 'add-plan-error');

  }
};

const handleCancel1 = () => {
  show4.value = false;
  formState1.value = {};
};

const handleDateConfirm = ({ selectedValues = [] }) => {
  formState1.value.signDate = selectedValues?.join('-');
  show1.value = false;
};

const handleTimeConfirm = ({ selectedValues = [] }) => {
  formState1.value.signTime = selectedValues?.join(':');
  show2.value = false;
}
const handleMatterConfirm = ({ selectedOptions = [] }) => {
  formState1.value.matter = selectedOptions?.[0]?.value;
  formState1.value.matterName = selectedOptions?.[0]?.text;
  show3.value = false;

}

onMounted(() => {
  init();
  planListInit();
  timer = setInterval(() => {
    currentTime.value = Date.now();
  }, 60000);
});
onBeforeUnmount(() => {
  clearInterval(timer);
});
</script>

<style lang="less" scoped>
.mine {
  &_header {
    width: 98%;
    box-sizing: border-box;
    padding: 8px;
    display: flex;
    align-items: center;

    &_info {
      width: 200px;
      margin-left: 16px;
      font-size: 14px;
      color: #333;
    }
  }
}

.card {
  height: 100px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  padding: 0 8px;

  &_img {
    width: 64px;
    height: 64px;
  }

  &_content {
    width: 200px;
    height: 84px;
    margin-left: 16px;
    &_matter{
      font-size: 14px;
      color: #333;
    }
    &_time{
      font-size: 12px;
      color: #666;
    }
    &_remark{
      font-size: 12px;
      color: #999;
    }
  }

}

.calendar {
  height: 460px;
}

.delete-button {
  height: 100%;
}
</style>
